package kr.co.kiso.usr.iv.sr.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import kr.co.kiso.usr.common.BaseController;
import kr.co.kiso.usr.iv.sr.service.IVSRService;
import kr.co.kiso.usr.iv.sr.vo.IVSRVo;
import kr.co.kiso.usr.utils.ConstValue;
import kr.co.kiso.usr.utils.PaginationInfo;
import kr.co.kiso.usr.utils.SMCommonUtil;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;

/**
 * 
 * 재무제표, 연결 재무제표, 영업보고서, IR자료 관리
 * @author devhw
 * 
 */
@Controller
@RequestMapping("/dsmgr/iv/sr/*")
public class IVSRController extends BaseController {
	@Autowired
	private IVSRService ivsrService;

	private final String FILE_PATH = ConstValue.TOP_UPLOAD+"/ivsr";

	Logger log = Logger.getLogger(getClass());
	
	/**
	 * 반환할 jsp 파일 정의
	 * @param vo
	 * @return
	 */
//	public ModelAndView getJspFile(IVSRVo vo, HttpServletRequest req){
//		ModelAndView mav = new ModelAndView();
//		StringBuffer jspFile= new StringBuffer();
////		jjp	:재무제표
////		cjp	:연결재무제표
//		if(vo.getIs_type().equals("jjp")//재무제표
//				||
//				vo.getIs_type().equals("cjp")//연결재무제표
//				){
//			return mav;
//		}else{
////		srp	:영업보고서
////		mrp	:월간리포트
////		arp	:annual report
////		ctb	:Fact Book
////		etc	:기타
//			log.debug("ets");
//			//게시판
//			String url = req.getServletPath();
//			url = url.replaceAll(".do", "");
//			
//			String[] urlSplit = url.split("/");
//			
//			for(int i=2; i<= urlSplit.length ;i++){
//				if(i==urlSplit.length){
//					jspFile.append("/");
//					jspFile.append(vo.getIs_type());
//					jspFile.append("/");
//					jspFile.append(urlSplit[i-1]);
//				}else{
//					jspFile.append("/");
//					jspFile.append(urlSplit[i-1]);
//				}
//			}
//		}
//		
//		log.debug("ets");
//		mav = new ModelAndView(jspFile.toString());
//		
//		return mav;
//	}
	/**
	 * 목록 화면
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView ivsr010Q(IVSRVo vo, HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		ModelAndView mav = new ModelAndView();
		
		if(vo.getSrc_is_title()!=null && !vo.getSrc_is_title().equals("")){
			vo.setSrc_is_title("%"+vo.getSrc_is_title()+"%");
		}
		if(vo.getSrc_value()!=null ){
			vo.setSrc_value("%"+vo.getSrc_value()+"%");
		}
		
		// 페이징 시작
		PaginationInfo paginationInfo = new PaginationInfo();
		int currnetPageNo = vo.getCurrentPageNo() <= 1 ? 1 : (Integer) vo
				.getCurrentPageNo();
		vo.setCurrentPageNo(currnetPageNo);
		vo.setParamMap(requestPram2Map(req));

		int iTotalCnt = ivsrService.ivsr010Q_cnt(vo);
		vo.setTotalRecordCount(iTotalCnt);
		
		if(iTotalCnt>0){
			List list = ivsrService.ivsr010Q(vo);
			
			List returnList = new ArrayList();
			for(int i=0; i < list.size(); i++){
				Map map = (Map) list.get(i);

				int fileCnt =Integer.parseInt(String.valueOf( map.get("file_cnt")));
				if(fileCnt>0){
					IVSRVo files = new IVSRVo();
					
					int is_seq_no = Integer.parseInt(String.valueOf( map.get("IS_SEQ_NO")));
					
					files.setIs_seq_no(is_seq_no);
					map.put("fileList", ivsrService.ivsr031Q(files));	
				}
				returnList.add(map);
				mav.addObject("list", returnList);
			}
			
			mav.addObject("pageHtml", vo.getToHtml("./ivsr010Q.do"));
			mav.addObject("paginationInfo", vo);
		}
		
		//공지 데이터 불러오기 불러오는 게시판 : IR  소식, 
		if(vo.getIs_type().equals("irs")
				|| vo.getIs_type().equals("irf")
				|| vo.getIs_type().equals("ent")
				
				){
			List list = ivsrService.ivsr011Q(vo);
			
			List returnList = new ArrayList();
			for(int i=0; i < list.size(); i++){
				Map map = (Map) list.get(i);

				int fileCnt =Integer.parseInt(String.valueOf( map.get("file_cnt")));
				if(fileCnt>0){
					IVSRVo files = new IVSRVo();
					
					int is_seq_no = Integer.parseInt(String.valueOf( map.get("IS_SEQ_NO")));
					
					files.setIs_seq_no(is_seq_no);
					map.put("fileList", ivsrService.ivsr031Q(files));	
				}
				returnList.add(map);
				mav.addObject("noticeList", returnList);
			}
		}
			

		return mav;
	}
	
	/**
	 * 등록 폼
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView ivsr020Q(IVSRVo vo, HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		//isMember(req,res);
		ModelAndView mav = new ModelAndView();

		return mav;
	}

	/**
	 * 등록 프로세스
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView ivsr020T(IVSRVo vo, HttpServletRequest req,
			HttpServletResponse res,MultipartHttpServletRequest mRqst) throws Exception {
		//isMember(req,res);
		
		MultiValueMap mulitFileMap = mRqst.getMultiFileMap();
		
		HashMap returnMap = new HashMap();
		
		SMCommonUtil util = new SMCommonUtil();
		util.mapToBean(req.getParameterMap(), vo);
		
		ModelAndView mav = new ModelAndView("redirect:./ivsr010Q.do?is_type="+vo.getIs_type());
	
		String usr_file_path= FILE_PATH;
		//첨부파일전송
		String[] files = {"file"};
		Map fileMap = util.getFileInfo(mulitFileMap, mRqst.getSession().getServletContext().getRealPath(""),usr_file_path,true, files);
		
		if("Y".equals((String)fileMap.get("error_yn"))){
			returnMap.put("error_msg", fileMap.get("error_msg"));
			mav.addObject("map",returnMap);
			return mav;
		}
		vo.setFile_map(fileMap);
		
//		vo.setFileList(fileList);
		//게시판 저장
		ivsrService.ivsr020T(vo);
		
		return mav;
	}
	
	/**
	 * ajax 파일 전송
	 * @param req
	 * @param res
	 * @param mRqst
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	@RequestMapping
	public ModelAndView isvr021T(HttpServletRequest req, HttpServletResponse res,MultipartHttpServletRequest mRqst) throws Exception {
		//isMember(req,res);
		ModelAndView mav = new ModelAndView("/common/toJson");
		Map returnMap = new HashMap();
		SMCommonUtil util = new SMCommonUtil();

		MultiValueMap mulitFileMap =  mRqst.getMultiFileMap();
		
		
		String usr_file_path= FILE_PATH+"/tmp";
		
		//첨부파일전송
		String[] files = {"cFile"};
		Map fileMap = util.getFileInfo(mulitFileMap, mRqst.getSession().getServletContext().getRealPath(""),usr_file_path,true, files);
		
		
		if("Y".equals((String)fileMap.get("error_yn"))){
			returnMap.put("error_msg", fileMap.get("error_msg"));
			mav.addObject("map",returnMap);
			return mav;
		}
		
		for(int i =0; i<files.length ; i++){
			if(null!=fileMap.get("cFile")){
				returnMap.put("file_nm", fileMap.get("cFile_nm"));
				returnMap.put("p_file_nm", fileMap.get("cFile"));
				returnMap.put("p_file_sz", fileMap.get("cFile_sz"));
			}
		}
		returnMap.put("error_yn", "N");
		
		//첨부파일전송
		String[] files2 = {"cFile2"};
		Map fileMap2 = util.getFileInfo(mulitFileMap, mRqst.getSession().getServletContext().getRealPath(""),usr_file_path,false, files2);
		
		
		if("Y".equals((String)fileMap2.get("error_yn"))){
			returnMap.put("error_msg", fileMap2.get("error_msg"));
			mav.addObject("map",returnMap);
			return mav;
		}
		
		
		for(int i =0; i<files2.length ; i++){
			if(null!=fileMap2.get("cFile2")){
				returnMap.put("file_nm", fileMap2.get("cFile2_nm"));
				returnMap.put("p_file_nm", fileMap2.get("cFile2"));
				returnMap.put("p_file_sz", fileMap2.get("cFile2_sz"));
			}
		}
		
		returnMap.put("error_yn", "N");
				
		mav.addObject("map",returnMap) ;
		
		return mav;
	}
	
	/**
	 * 상세조회 페이지
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView ivsr030Q(IVSRVo vo, HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		//isMember(req,res);
		ModelAndView mav =  new ModelAndView();

		mav.addObject("map", ivsrService.ivsr030Q(vo));
		mav.addObject("fileList", ivsrService.ivsr031Q(vo));	
		
		mav.addObject("nextInfo", ivsrService.ivsr032Q(vo));
		return mav;
	}
	
	/**
	 * 수정 프로세스
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView ivsr040T(IVSRVo vo, HttpServletRequest req,
			HttpServletResponse res,MultipartHttpServletRequest mRqst) throws Exception {
		//isMember(req,res);

		MultiValueMap mulitFileMap = mRqst.getMultiFileMap();
		
		HashMap returnMap = new HashMap();
		
		SMCommonUtil util = new SMCommonUtil();
		util.mapToBean(req.getParameterMap(), vo);
		
		ModelAndView mav = new ModelAndView("redirect:./ivsr030Q.do?is_type="+vo.getIs_type()+"&is_seq_no="+vo.getIs_seq_no()+"&currentPageNo="+vo.getCurrentPageNo() );
	
		String usr_file_path= FILE_PATH;
		//첨부파일전송
		String[] files = {"file"};
		Map fileMap = util.getFileInfo(mulitFileMap, mRqst.getSession().getServletContext().getRealPath(""),usr_file_path,true, files);
		
		if("Y".equals((String)fileMap.get("error_yn"))){
			returnMap.put("error_msg", fileMap.get("error_msg"));
			mav.addObject("map",returnMap);
			return mav;
		}
		vo.setFile_map(fileMap);
		
		//게시판 수정
		ivsrService.ivsr040T(vo, mRqst.getSession().getServletContext().getRealPath(""));
//		String mimedata = req.getParameter("content_html");
//		if(mimedata != null){
//			DEXTWebEditor DEXTMime = new DEXTWebEditor();
//
//			File folFile = new File(req.getSession().getServletContext().getRealPath("")+File.separator+ConstValue.EDITOR_FOLDER);
//			if(!folFile.exists()){
//				folFile.mkdirs();
//			}
//			
//			mimedata = DEXTMime.DEXTMimeDecode(mimedata, req.getSession().getServletContext().getRealPath("")+File.separator+ConstValue.EDITOR_FOLDER+File.separator, ConstValue.UPLOAD_URL);
//			
//			vo.setContent(mimedata);
//		}
//
//
//		ModelAndView mav = new ModelAndView("redirect:./ivsr030Q.do?is_type="+vo.getIs_type()+"&is_seq_no="+vo.getIs_seq_no()+"&currentPageNo="+vo.getCurrentPageNo() );
//
//		//수정프로세스
//		ivsrService.ivsr040T(vo);
//		
//		//기존 파일 삭제
//		ivsrService.ivsr041T(vo);
//		
//
//		String[] cFiles = vo.getcFiles();
//		String[] p_cFiles = vo.getP_cFiles();
//		String[] cFiles_size = vo.getcFiles_size();
//		
//		//첨부 이미지
//		String[] cFiles2 = vo.getcFiles2();
//		String[] p_cFiles2 = vo.getP_cFiles2();
//		String[] cFiles_size2 = vo.getcFiles_size2();
//
//		
//		//영업보고서일때는 첨부이미지가 있어서 첨부파일은 구분자가 1 첨부이미지는 2
//		if(vo.getIs_type().equals("srp")|| 
//				vo.getIs_type().equals("mrp")
//				|| vo.getIs_type().equals("arp")
//				|| vo.getIs_type().equals("ctb")
//				){
//			vo.setFile_type("1");
//		}
//		if(cFiles !=null){
//			for(int i=0; i< cFiles.length; i++){
//				vo.setFile_seq_no(ivsrService.dstd021Q(vo));
//				
//				vo.setM_file_nm(p_cFiles[i]);
//				vo.setV_file_nm(cFiles[i]);
//				vo.setFile_size(cFiles_size[i]);
//				
//				ivsrService.dstd021T(vo);	
//			}
//		}
//		if(vo.getIs_type().equals("srp")|| 
//				vo.getIs_type().equals("mrp")
//				|| vo.getIs_type().equals("arp")
//				|| vo.getIs_type().equals("ctb")
//				){
//			vo.setFile_type("2");
//		}
//		if(cFiles2 !=null){
//			for(int i=0; i< cFiles2.length; i++){
//				vo.setFile_seq_no(ivsrService.dstd021Q(vo));
//				
//				vo.setM_file_nm(p_cFiles2[i]);
//				vo.setV_file_nm(cFiles2[i]);
//				vo.setFile_size(cFiles_size2[i]);
//				
//				ivsrService.dstd021T(vo);	
//			}
//		}
//		
		return mav;
	}
	
	/**
	 * 게시글 삭제
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView ivsr050T(IVSRVo vo, HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		//isMember(req,res);
		ModelAndView mav = new ModelAndView("redirect:./ivsr010Q.do?is_type="+vo.getIs_type()+"&currentPageNo="+vo.getCurrentPageNo() );

		List fileList = ivsrService.ivsr031Q(vo);
		
		if(fileList!=null && fileList.size()>0){
			for(int i =0; i < fileList.size() ; i++){
				Map map = (Map) fileList.get(i);
				if(map.get("m_file_nm")!=null){
					File delFile = new File(req.getSession().getServletContext().getRealPath("")+(String)map.get("m_file_nm"));
					if(delFile.isFile()){
						delFile.delete();
					}	
				}
			}
		}
		//파일삭제
		ivsrService.ivsr041T(vo);
		//본문 삭제
		ivsrService.ivsr050T(vo);
		
		return mav;
	}
	
	/**
	 * 상세보기 수정전에 view 페이지
	 * @param vo
	 * @param req
	 * @param res
	 * @return
	 * @throws Exception
	 */
	@RequestMapping
	public ModelAndView ivsr060Q(IVSRVo vo, HttpServletRequest req,
			HttpServletResponse res) throws Exception {
		//isMember(req,res);
		ModelAndView mav =  new ModelAndView();

		mav.addObject("map", ivsrService.ivsr030Q(vo));
		mav.addObject("fileList", ivsrService.ivsr031Q(vo));	
		
//		mav.addObject("nextInfo", );
		List nextList = ivsrService.ivsr032Q(vo);
		if(nextList!=null && nextList.size()>0){
			for(int i=0; i< nextList.size();i++){
				Map next = (Map) nextList.get(i);
				if("1".equals(String.valueOf( next.get("type")))){
//					이전
					mav.addObject("nextInfo1", next);	
				}else{
//					다음
					mav.addObject("nextInfo2", next);
				}
			}
		}
		return mav;
	}
}
